package com.jd.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public int getOrder() {
        return -1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("custom global filter");
        ServerHttpRequest request =  exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();   
        String path = request.getURI().getPath();
        System.out.println("访问的接口：" + path);
        if (!getAuthoritiesResources(path)) {
            return Mono.error(new Throwable("没有访问权限"));
        }
        long start = System.currentTimeMillis();
        return chain.filter(exchange)
                // then的内容会在过滤器返回的时候执行，即最后执行
                .then(Mono.fromRunnable(() -> System.out
                        .println(String.format(" %s  接口的访问耗时：%s /ms", path, System.currentTimeMillis() - start))));
    }
    
    /**
     * 模拟调用资源服务器鉴权
     * @param path
     * @return
     */
    private Boolean getAuthoritiesResources(String path){
        if (path.contains("admin/order") || path.contains("oauth") ) {
            return true;
        }
        return false;
    }

}
